import 'dart:async';

// 防抖函数(停止触发后执行一次，如搜索防抖)
Function debounce(Function func, [int delay = 500]) {
  Timer? timer;
  return ([Object? arg]) {
    if (timer?.isActive ?? false) {
      timer!.cancel(); // 取消之前的定时器
    }
    timer = Timer(Duration(milliseconds: delay), () {
      Function.apply(func, arg == null ? null : [arg]);
      timer = null;
    }); // 设置新的定时器
  };
}

// 节流函数(固定时间内只触发一次，如点击防抖)
Function throttle(Function func, [delay = 1500, leading = true]) {
  Timer? timer;
  return ([Object? arg]) {
    if (timer == null) {
      timer = Timer(Duration(milliseconds: delay), () {
        if (!leading) Function.apply(func, arg == null ? null : [arg]);
        timer = null;
      });
      if (leading) Function.apply(func, arg == null ? null : [arg]);
    }
  };
}
